<template>
    <div class="app-container">
        <div :class="['filter-container']">

            <el-form ref="form" :inline="true" label-width="60px">
                <el-form-item>
                    <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download"
                        @click="handleDownload">
                        前端导出
                    </el-button>
                    <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download"
                        @click="handleDownloadGet">
                        后端get导出
                    </el-button>
                    <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download"
                        @click="handleDownloadPost">
                        前端post导出
                    </el-button>
                </el-form-item>
            </el-form>

        </div>

        <div :class="['table']">
            <div class="table-container">
                <el-table :key="tableKey" v-loading="listLoading" height="100%" :data="list" border fit highlight-current-row
                    style="width: 100%;" @sort-change="sortChange">
                    <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
                        <template slot-scope="{row}">
                            <span>{{ row.id }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="日期" width="150px" align="center">
                        <template slot-scope="{row}">
                            <span>{{ row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="标题" min-width="150px">
                        <template slot-scope="{row}">
                            <span class="link-type" @click="handleUpdate(row)">{{ row.title }}</span>
                            <el-tag>{{ row.type | typeFilter }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="作者" width="110px" align="center">
                        <template slot-scope="{row}">
                            <span>{{ row.author }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="Imp" width="80px">
                        <template slot-scope="{row}">
                            <svg-icon v-for="n in + row.importance" :key="n" icon-class="star" class="meta-item__icon" />
                        </template>
                    </el-table-column>
                    <el-table-column label="状态" class-name="status-col" width="100">
                        <template slot-scope="{row}">
                            <el-tag :type="row.status | statusFilter">
                                {{ row.status }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
                        <template slot-scope="{row,$index}">
                            <el-button type="primary" size="mini" @click="handleUpdate(row)">
                                编辑
                            </el-button>
                            <el-button v-if="row.status!='published'" size="mini" type="success">
                                发布
                            </el-button>
                            <el-button v-if="row.status!='draft'" size="mini">
                                选中
                            </el-button>
                            <el-button v-if="row.status!='deleted'" size="mini" type="danger">
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>

        <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    </div>
</template>

<script>
import { fetchList, createArticle, updateArticle } from '@/api/article'
import waves from '@/directive/waves' // waves directive
import axios from 'axios' // 引入axios
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination 分页组件

const calendarTypeOptions = [
    { key: 'CN', display_name: 'China' },
    { key: 'US', display_name: 'USA' },
    { key: 'JP', display_name: 'Japan' },
    { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name
    return acc
}, {})

export default {
    name: 'LayoutTable',
    components: { Pagination },
    directives: { waves }, // 指令
    filters: {
        statusFilter (status) {
            const statusMap = {
                published: 'success',
                draft: 'info',
                deleted: 'danger'
            }
            return statusMap[status]
        },
        typeFilter (type) {
            return calendarTypeKeyValue[type]
        }
    },
    data () {
        return {
            // 筛选框的 form 表单

            tableKey: 0,
            list: null, // 表格数据
            total: 0, // 总条数
            listLoading: true, // 表格加载数据时的 loading
            listQuery: { // 表格当前页 和 当前页的展示数量
                page: 1,
                limit: 20
            },
            downloadLoading: false // 导出按钮 的 loading
        }
    },
    created () {
        this.getList()
    },
    methods: {
        // 获取表格数据
        getList () {
            this.listLoading = true
            fetchList(this.listQuery).then(response => {
                this.list = response.data.items
                this.total = response.data.total
                // Just to simulate the time of the request
                setTimeout(() => {
                    this.listLoading = false
                }, 1.5 * 1000)
            })
        },
        // 重新获取表格数据 页码归为1
        handleFilter () {
            this.listQuery.page = 1
            this.getList()
        },
        // 排序
        sortChange (data) {
            console.log(data)
            const { prop, order } = data
            if (prop === 'id') {
                this.sortByID(order)
            }
        },
        sortByID (order) {
            if (order === 'ascending') {
                this.listQuery.sort = '+id'
            } else {
                this.listQuery.sort = '-id'
            }
            // 想参数中添加 排序方式后 再次向后台请求
            this.handleFilter()
        },
        // 导出 表格数据
        handleDownload () {
            this.downloadLoading = true
            // 调用 Excel 导出表格的工具
            import('@/vendor/Export2Excel').then(excel => {
                const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
                const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
                const data = this.formatJson(filterVal)
                excel.export_json_to_excel({
                    header: tHeader,
                    data,
                    filename: 'table-list'
                })
                this.downloadLoading = false
            })
        },
        // 获取导出表格的数据
        formatJson (filterVal) {
            return this.list.map(v => filterVal.map(j => {
                if (j === 'timestamp') {
                    return parseTime(v[j])
                } else {
                    return v[j]
                }
            }))
        },
        // 后端处理导出 get
        getSortClass: function (key) {
            const sort = this.listQuery.sort
            return sort === `+${key}` ? 'ascending' : 'descending'
        },
        handleDownloadGet () {
            const baseUrl = 'http//'
            const url = `${baseUrl}/salaryDet/salSalarydetTax/export?&abspayMonth=${this.dataForm.actualDate}&name=${this.dataForm.nameAndIdcard}&payMonth=${this.dataForm.payableDate}&type=${this.dataForm.type}&code=${this.treeData.code ? this.treeData.code : 1}`
            const link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            // link.setAttribute('download', 'xxx.xlsx');
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
        },
        // 后端处理导出 post
        handleDownloadPost () {
            axios({
                method: 'post',
                url: 'proxyApi/biom/teacher/batchDownload',
                data: this.dataForm,
                headers: { 'Authorization': this.$cookie.get('token') },
                responseType: 'blob'
            }).then(response => {
                // debugger
                const blob = new Blob([response.data], { type: 'application/zip ' })
                const url = window.URL.createObjectURL(blob)
                const link = document.createElement('a') // 创建a标签
                link.href = url
                const fileName = response.headers['content-disposition'].split('=')[1]
                link.download = fileName // 文件重命名，若无需重命名，将该行删去
                console.log(link)
                link.click()
                // URL.revokeObjectURL(url) // 释放内存
                console.log(response.data.type)
                if (response.data.type === 'application/octet-stream') {
                    // 获取http头部的文件名信息，若无需重命名文件，将下面这行删去
                    const fileName = response.headers['content-disposition'].split('=')[1]
                    console.log('fileName', fileName)
                    /* 兼容ie内核，360浏览器的兼容模式 */
                    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                        const blob = new Blob([response.data], { type: 'application/zip' })
                        window.navigator.msSaveOrOpenBlob(blob, fileName)
                    } else {
                        /* 火狐谷歌的文件下载方式 */
                        const blob = new Blob([response.data], { type: 'application/zip' })
                        const url = window.URL.createObjectURL(blob)
                        const link = document.createElement('a') // 创建a标签
                        link.href = url
                        link.download = fileName // 文件重命名，若无需重命名，将该行删去
                        link.click()
                        URL.revokeObjectURL(url) // 释放内存
                    }
                    resolve(response)
                } else {
                    const reader = new FileReader()
                    reader.onload = function (event) {
                        const msg = JSON.parse(reader.result).data
                        this.$errorMsg('0000', message) // 将错误信息显示出来
                    }
                    reader.readAsText(response.data)
                }
            })
        }
    }
}
</script>
<style lang="scss" scoped>
//表格布局的注释：
//$rowLength 这个变量表示了 筛选的搜索框会有多少行，由于在不同宽度显示器下 所占行数会不一定 ，所以下面使用媒体查询 做兼容
//最小兼容至 1366
@import '~@/styles/layout-table.scss';
$rowLength: 2;
@media all and (min-width: 1659px) {
    $rowLength: 2;
    @include calculation($rowLength: $rowLength);
}
@media all and (max-width: 1659px) {
    $rowLength: 3;
    @include calculation($rowLength: $rowLength);
}
</style>
